﻿$.extend($HASH, {
    page: {},
    siteModule: '',
    savePages: {},
    recently: storage.get('recently_' + $HASH['site']['id']) || [],
    historySiteTamplates: storage.get('historySiteTamplates_' + $HASH['site']['id']) || [],
    historyPageTamplates: storage.get('historyPageTamplates_' + $HASH['site']['id']) || [],
    historyPageSkins: storage.get('historyPageSkins_' + $HASH['site']['id']) || [],
    iframeScrollTop: 0
});
function updateHistory(key, data) {
    if (!key) return;
    if (data) {
        $HASH[key] = removeArray($HASH[key], data);
        $HASH[key].unshift(data);
        if ($HASH[key].length > historyMax) {
            $HASH[key].pop()
        };
        storage.set(key + '_' + $HASH['site']['id'], $HASH[key])
    } else {
        $HASH[key] = [];
        storage.remove(key + '_' + $HASH['site']['id'])
    }
};
var mainContainer = $('#mainContainer'),
frameContainer = $('#frameContainer'),
siteTab = $('#siteTab'),
siteTabBox = $('#siteTabBox'),
siteTabSlide = $('#siteTabSlide'),
welcome = false,
topFrameId = 0,
activeFrameId = -1;
function showWelcome() {
    createFrame(welcomePage, welcomeTitle);
    welcome = true
};
function newFrame(url, id, role) {
    $('<div id="frameWrapper_' + id + '" class="frameWrapper ' + ((supportTouch && role != 'page') ? 'touch' : '') + '"><iframe src="' + url + '"  frameborder="0" id="frame_' + id + '" scrolling="auto"></iframe></div>').appendTo(frameContainer).load(function () { })
};
function createFrame(url, title, role, id) {
    if ($(window).width() < 768) {
        if (!$('#frame_phone').length) {
            newFrame(url, 'phone', role);
            $('#frameWrapper_phone').addClass('active')
        } else {
            $('#frame_phone').attr('src', url)
        };
        window.location.href = '/c/admin#' + url + '|' + title + '|';
        return
    };
    var frame = $HASH['frames'][url];
    title = title ? title : $lan['admin']['newTab'];
    if (!frame) {
        if (url == welcomePage) {
            frameId = 'welcome'
        } else if (id) {
            frameId = id
        } else {
            topFrameId++;
            frameId = topFrameId
        };
        newFrame(url, frameId, role);
        frame = {
            frameId: frameId,
            title: title,
            url: url
        };
        $HASH['frames'][url] = frame;
        var newTab = $('<li id="tab_' + frameId + '" role="' + role + '"><i class="icon-spinner" ></i><i class="siteTabClose" ></i><p class="siteTabTitle">' + title + '</p></li>').data({
            id: frameId,
            url: url
        }).appendTo(siteTabBox);
        resetTab()
    };
    selectTab(frame['frameId']);
    if (welcome) {
        closeTab('welcome')
    };
    welcome = false
};
function selectTab(id, url) {
    $('#tab_' + id).toActive();
    $('#frameWrapper_' + id).toActive();
    activeFrameId = id;
    resizeTab()
};
function saveTab(id, callBack) {
    if ($HASH.savePages[id]) {
        $HASH.savePages[id](callBack)
    }
};
function setSave(id, val, fn) {
    $('#tab_' + id).data('checkSave', val);
    if (fn) {
        $HASH.savePages[id] = fn
    }
};
function closeTab(id, url, noSave) {
    if (id == 'welcome' && $('li', siteTabBox).length == 1) return;
    if (!id) {
        if (url && $HASH['frames'][url]) {
            id = $HASH['frames'][url]['frameId']
        } else {
            return
        }
    };
    var fn = function () {
        var backTab;
        if (activeFrameId == id && $('#tab_' + id).siblings().length) {
            backTab = $('#tab_' + id).next().length ? $('#tab_' + id).next() : $('#tab_' + id).prev()
        };
        delete $HASH['frames'][$('#tab_' + id).data('url')];
        delete $HASH.savePages[id];
        $('#tab_' + id).remove();
        $('#frameWrapper_' + id).remove();
        if (backTab) {
            selectTab(backTab.data('id'))
        } else if (activeFrameId == id) {
            showWelcome()
        };
        resetTab()
    };
    if (!noSave) {
        if ($('#tab_' + id).data('checkSave')) {
            Confirm('该页面有未保存的改动，是否先保存？',
            function () {
                saveTab(id, fn)
            },
            fn, {
                confirmText: '保存后关闭',
                cancelText: '不保存'
            })
        } else {
            fn()
        }
    } else {
        fn()
    }
};
function freshTab(id) {
    if (document.getElementById('frame_' + id).contentWindow) {
        document.getElementById('frame_' + id).contentWindow.location.reload()
    }
};
function tabRename(id, name) {
    $('#tab_' + id + ' p').text(name);
    resetTab()
};
function resetTab() {
    if ($('li', siteTabBox).length == 1 && $('li', siteTabBox).data('id') == 'welcome') {
        mainContainer.removeClass('showTab')
    } else {
        mainContainer.addClass('showTab')
    };
    var tw = 0;
    $('li', siteTabBox).each(function () {
        tw += $(this).outerWidth()
    });
    siteTabBox.width(tw)
};
function resizeTab() {
    if (!$('li', siteTabBox).length) {
        siteTabSlide.hide();
        siteTab.removeClass('slide');
        $('a', siteTabSlide).removeClass('active');
        return
    } else {
        if (siteTabBox.width() > $(window).width()) {
            siteTab.addClass('slide');
            slideTab()
        } else {
            siteTab.removeClass('slide');
            $('a', siteTabSlide).removeClass('active');
            if (siteTabBox.offset().left < 0) {
                moveTab(0)
            }
        }
    }
};
function slideTab(num) {
    var l = siteTabBox.position().left,
    ww = siteTabBox.parent().width(),
    sw = siteTabBox.width();
    l = num ? l + ww * num : -$('li.active', siteTabBox).position().left + Math.floor(ww / 2);
    if (l + sw < ww) {
        l = ww - sw
    };
    if (l >= 0) {
        l = 0
    };
    $('a', siteTabSlide).removeClass('active');
    moveTab(l)
};
function moveTab(num) {
    var fn = function () {
        if (num < 0) {
            $('a.left', siteTabSlide).addClass('active')
        };
        if (-num + siteTabBox.parent().width() < siteTabBox.width()) {
            $('a.right', siteTabSlide).addClass('active')
        }
    };
    if (num == siteTabBox.position().left) {
        fn();
        return
    } else {
        siteTabBox.stop().animate({
            left: num
        },
        'fast', 'easeOut',
        function () {
            if (siteTab.hasClass('slide')) {
                siteTabBox.css('left', num);
                fn()
            }
        })
    }
};
siteTabBox.delegate('li', click,
function (e) {
    selectTab($(this).data('id'))
}).delegate('i.siteTabClose', click,
function (e) {
    closeTab($(this).parent().data('id'));
    e.preventDefault();
    e.stopPropagation()
}).delegate('i.icon-spinner', click,
function (e) {
    freshTab($(this).parent().data('id'));
    e.preventDefault();
    e.stopPropagation()
});
siteTabSlide.delegate('a.right.active', click,
function () {
    slideTab(-1)
}).delegate('a.left.active', click,
function () {
    slideTab(1)
});
function resizeNav() {
    if ($(window).width() >= 768) {
        $('#nav').css('left', 55)
    } else {
        $('#nav').css('left', -$('#nav').width())
    };
    $('#nav').removeClass('active');
    $('#navMask').hide();
    $('#bodyMargin').css({
        'margin-left': 0
    });
    closeNavList()
};
function openNav() {
    $('#bodyMargin').animate({
        'margin-left': $('#nav').width()
    },
    'normal', 'easeOut');
    $('#nav').addClass('active').animate({
        'left': 0
    },
    'normal', 'easeOut');
    $('#navMask').show()
};
function closeNav(callBack) {
    if ($('#nav').offset().left == 0) {
        $('#bodyMargin').animate({
            'margin-left': 0
        },
        'normal', 'easeOut');
        $('#nav').animate({
            'left': -$('#nav').width()
        },
        'normal', 'easeOut',
        function () {
            $('#nav').css('left', -$('#nav').width()).removeClass('active');
            $('#navMask').hide();
            fireHandler(callBack)
        })
    }
};
function showNavList(el) {
    var fn = function () {
        if (el.parent().data('page') && !pageContainer.data('loaded')) {
            $('li:first', pageTabs).trigger(click)
        };
        setNavScroll(el.parent().find('div[role="scroll"]'))
    };
    el.parent().addClass('active');
    if ($('#nav').hasClass('active')) {
        if (!el.next().find('ul li.nb_back').length) {
            $('<li class="hidden-desktop nb_back"><a href="javascript:;" class="nb_levelLink">' + $lan['back'] + '</a></li>').prependTo(el.next().find('ul'))
        };
        el.next().css('left', -$('#nav').width()).animate({
            left: 0
        },
        'normal', 'easeOut', fn)
    } else {
        el.next().css('left', 0);
        fn()
    }
};
function closeNavList() {
    var activeNav = $('#nav li.nb_levelLi.active');
    if ($('div[role="scroll"]', activeNav).getNiceScroll()) {
        $('div[role="scroll"]', activeNav).getNiceScroll().remove()
    };
    if ($(window).width() >= 768) {
        activeNav.removeClass('active')
    } else {
        $('> div', activeNav).animate({
            left: -$('#nav').width()
        },
        'normal', 'easeOut',
        function () {
            activeNav.removeClass('active')
        })
    }
};
function setNavScroll(el) {
    var cHeight = el.data('page') ? 361 : $(window).height() - 34;
    if ($(el).children().height() > cHeight || el.data('page')) {
        el.height(cHeight);
        el.niceScroll({
            autohidemode: true,
            bouncescroll: true,
            zindex: 101,
            cursorwidth: 5,
            railpadding: {
                top: 0,
                right: 0,
                left: 0,
                bottom: 0
            }
        })
    } else {
        el.height('auto')
    }
};
$('#nav').delegate('li.nb_levelLi > a', click,
function (e) {
    if ($(this).parent().hasClass('active')) {
        closeNavList()
    } else {
        closeNavList();
        showNavList($(this))
    };
    e.preventDefault();
    e.stopPropagation()
});
$('#phoneNav').on(click,
function (e) {
    openNav();
    e.preventDefault();
    e.stopPropagation()
});
$('#navMask').on(click,
function (e) {
    closeNav()
});
$('body').delegate('a[url]', click,
function (e) {
    var $this = $(this),
    fn = function () {
        createFrame($this.attr('url'), $this.text(), $this.attr('role'))
    };
    e.preventDefault();
    if ($('#nav').hasClass('active')) {
        closeNav(fn);
        e.stopPropagation()
    } else {
        fn();
        closeNavList()
    }
}).delegate('li.nb_back', click,
function (e) {
    closeNavList();
    e.preventDefault();
    e.stopPropagation()
}).delegate('div.nb_title', click,
function (e) {
    closeNavList();
    $(this).toggleClass('active').siblings().removeClass('active');
    e.stopPropagation()
}).on(click,
function () {
    $('div.nb_title').removeClass('active')
}); (function () {
    $HASH['fullscreen'] = null;
    $HASH['fullscreenchange'] = {};
    var fullScreenApi = {
        supportsFullScren: false,
        isFullScreen: function () {
            return false
        },
        requestFullScreen: function () { },
        cancelFullScreen: function () { },
        fullscreenchange: function () { },
        prefix: ''
    };
    browserPrefixes = 'webkit moz o ms khtml'.split(' ');
    if (typeof document.cancelFullScreen != 'undefined') {
        fullScreenApi.supportsFullScren = true
    } else {
        for (var i = 0, il = browserPrefixes.length; i < il; i++) {
            fullScreenApi.prefix = browserPrefixes[i];
            if (typeof document[fullScreenApi.prefix + 'CancelFullScreen'] != 'undefined') {
                fullScreenApi.supportsFullScreen = true;
                break
            }
        }
    };
    if (fullScreenApi.supportsFullScreen) {
        fullScreenApi.fullScreenEventName = fullScreenApi.prefix + 'fullscreenchange';
        fullScreenApi.isFullScreen = function () {
            switch (this.prefix) {
                case '':
                    return document.fullScreen;
                case 'webkit':
                    return document.webkitIsFullScreen;
                default:
                    return document[this.prefix + 'FullScreen']
            }
        };
        fullScreenApi.requestFullScreen = function (el) {
            if (el.id) $HASH['fullscreen'] = el.id;
            return (this.prefix === '') ? el.requestFullScreen() : el[this.prefix + 'RequestFullScreen']()
        };
        fullScreenApi.fullscreenchange = function (el, callBack) {
            if (!typeof callBack == 'function' || !el.id) return;
            var fn = this.prefix === '' ? 'fullscreenchange' : this.prefix + 'fullscreenchange';
            $HASH['fullscreenchange'][el.id] = callBack;
            document.addEventListener(fn,
            function () {
                if ($HASH['fullscreen'] && $HASH['fullscreenchange'][$HASH['fullscreen']]) {
                    $HASH['fullscreenchange'][$HASH['fullscreen']](window.fullScreenApi.isFullScreen())
                };
                if (!window.fullScreenApi.isFullScreen()) {
                    $HASH['fullscreen'] = null
                }
            },
            false)
        };
        fullScreenApi.cancelFullScreen = function (el) {
            $HASH['fullscreen'] = null;
            return (this.prefix === '') ? el.cancelFullScreen() : el[this.prefix + 'CancelFullScreen']()
        }
    };
    window.fullScreenApi = fullScreenApi
})();
$.requestFullScreen = function (id) {
    if (window.fullScreenApi.supportsFullScreen) {
        window.fullScreenApi.requestFullScreen(document.getElementById(id))
    } else {
        lowBrowser()
    }
};
$.fullscreenchange = function (id, callBack) {
    if (window.fullScreenApi.supportsFullScreen) {
        window.fullScreenApi.fullscreenchange(document.getElementById(id), callBack)
    }
};
$.cancelFullScreen = function () {
    if (window.fullScreenApi.supportsFullScreen) {
        window.fullScreenApi.cancelFullScreen(document)
    }
};
$.fullscreenchange('body',
function (flag) {
    if (flag) {
        $('#rightMenu div[role="requestFullScreen"]').hide();
        $('#rightMenu div[role="cancelFullScreen"]').show()
    } else {
        $('#rightMenu div[role="requestFullScreen"]').show();
        $('#rightMenu div[role="cancelFullScreen"]').hide()
    }
});
$('#rightMenu').delegate('div[role]', click,
function (e) {
    var $this = $(this);
    $this.hideTips();
    if ($this.hasClass('disabled')) return;
    switch ($(this).attr('role')) {
        case 'requestFullScreen':
            $.requestFullScreen('body');
            break;
        case 'cancelFullScreen':
            $.cancelFullScreen('body');
            $('#rightMenu div[role="requestFullScreen"]').show();
            $('#rightMenu div[role="cancelFullScreen"]').hide();
            break;
        case 'preview':
            var url = $('li[role="page"].active', siteTabBox).length ? 'http://' + $HASH['site']['host'] + viewURL + $('li[role="page"].active', siteTabBox).data('id') : 'http://' + $HASH['site']['host'];
            window.open(previewURL + url);
            break;
        case 'message':
            createFrame($(this).attr('url'), '通知');
            break;
        default:
            return false;
            break
    };
    e.preventDefault()
});
$('#navHeader').on(click,
function () {
    if (!$('#nav').hasClass('active')) {
        closeNavList()
    }
});
$(window).resize(function () {
    resizeTab();
    resizeNav();
    closeNavList()
});
var pageContainer = $('#pageContainer'),
pageTabs = $('#pageTabs'),
pageScrollContainer = $('#pageScrollContainer'),
addPage = $('#addPage'),
appPage = $('#appPage');
appPage.delegate('dt', click,
function (e) {
    $(this).toggleClass('on');
    if ($(this).hasClass('on')) {
        $(this).next().hide()
    } else {
        $(this).next().show()
    };
    resizeScroll(pageScrollContainer)
});
addPage.on(click,
function () {
    createPage(function (backData) {
        insertPage(backData).insertAfter($('#customPage li:first'));
        resizeScroll(pageScrollContainer);
        pageScrollContainer.scrollTop(1)
    })
});
$('li', pageTabs).litabs({
    index: -1,
    callBack: function (el) {
        var role = el.attr('role'),
        target = $('#' + role + 'Page');
        target.show().siblings().hide();
        if (!el.data('loaded')) {
            target.html(getContentLoading());
            var action = role == 'custom' ? 'getCustomPage' : 'getAppPage';
            rpcJSON(action, {},
            function (data) {
                pageContainer.data('loaded', 1);
                el.data('loaded', 1);
                var html = '';
                if (data.length) {
                    html = role == 'custom' ? setCustomPage(data) : setAppPage(data)
                } else {
                    html = getEmptyContent()
                };
                target.html(html);
                resizeScroll(pageScrollContainer)
            },
            function () {
                target.html(getEmptyContent())
            })
        } else {
            resizeScroll(pageScrollContainer)
        };
        pageScrollContainer.scrollTop(1);
        if (role == 'custom') {
            addPage.show()
        } else {
            addPage.hide()
        }
    }
});
var setHomepage = function (id, callBack) {
    rpc('setHomepage', {
        pageId: id
    },
    callBack)
},
setMenu = function (id, value, callBack) {
    rpc('setMenu', {
        pageId: id,
        value: value
    },
    callBack)
},
copyPage = function (id, callBack) {
    rpcJSON('copyPage', {
        pageId: id
    },
    function (data) {
        callBack(data)
    })
},
insertPage = function (item) {
    var el = $('<li data-id="' + item.id + '" class="new">' + '<span class="nb_leveIcon ' + (item.homePage ? 'active' : '') + '" title="' + (item.homePage ? $lan['homePage'] : $lan['admin']['setHomePage']) + '" role="setHomepage" ><i class="icon-home" ></i></span>' + '<span class="nb_leveIcon ' + (item.navPage ? 'active' : '') + '" title="' + (item.navPage ? $lan['admin']['cancelNavPage'] : $lan['admin']['setNavPage']) + '" role="setMenu"><i class="icon-menu"></i></span>' + '<div class="nb_leveWebName">' + item.name + '</div>' + '<span class="nb_leveTool">' + '<i title="' + $lan['admin']['set'] + '" class="icon-cog" role="set"></i>' + '<i title="' + $lan['admin']['viewURL'] + '" class="icon-link" role="viewUrl"></i>' + '<i title="' + $lan['admin']['rename'] + '" class="icon-pencil" role="rename"></i>' + '<i title="' + $lan['admin']['copy'] + '" class="icon-copy" role="copy"></i>' + '<i title="' + $lan['admin']['delete'] + '" class="icon-remove" role="del"></i>' + '</span>' + '</li>');
    return el
},
createPage = function (callBack) {
    rpcJSON('createPage', {},
    function (data) {
        callBack(data)
    })
},
delPage = function (data, callBack) {
    Confirm('删除后不可恢复，确定要删除这个页面吗？',
    function () {
        $HASH['recently'] = removeArray($HASH['recently'], data);
        storage.set('recently_' + $HASH['site']['id'], $HASH['recently']);
        rpcJSON('delPage', {
            pageId: data.id
        },
        function (data) {
            callBack(data)
        })
    })
},
renamePage = function (id, name, callBack) {
    rpc('renamePage', {
        pageId: id,
        pageName: name
    },
    callBack)
},
resetPageName = function (id, name) {
    var pageLi = $('#customPage li[data-id="' + id + '"]'),
    nameEl = pageLi.find('div.nb_leveWebName');
    if (pageLi.find('span[role="setMenu"]').hasClass('active')) {
        reloadPageNav()
    };
    if ($HASH['frames'][pageURL + id]) {
        tabRename(id, name)
    };
    nameEl.text(name)
};
pageScrollContainer.delegate('span[role],i[role]', click,
function (e) {
    e.preventDefault();
    e.stopPropagation();
    var $this = $(this),
    $parent = $(this).parents('li:first'),
    id = $parent.data('id');
    switch ($this.attr('role')) {
        case 'viewUrl':
            var url = viewURL + $parent.data('id'),
            url1 = 'http://' + $HASH['site']['host'] + url;
            Alert('当前页面站内地址：<br>' + url + '<br><br>网络访问地址：<br>' + url1, '', {
                width: 650
            });
            break;
        case 'setHomepage':
            if (!$this.hasClass('active')) {
                setHomepage($parent.data('id'),
                function () {
                    var homePage = pageContainer.find('span[role="setHomepage"].active');
                    homePage.removeClass('active');
                    $this.addClass('active');
                    $parent.insertBefore(homePage.parent());
                    Tips('success', '首页设置成功')
                })
            };
            break;
        case 'setMenu':
            if ($this.hasClass('active')) {
                setMenu(id, 0,
                function () {
                    reloadPageNav();
                    $this.removeClass('active').attr('title', $lan['admin']['setNavPage']);
                    Tips('success', '取消导航项成功')
                })
            } else {
                setMenu(id, 1,
                function () {
                    reloadPageNav();
                    $this.addClass('active').attr('title', $lan['admin']['cancelNavPage']);
                    Tips('success', '设置导航项成功')
                })
            };
            break;
        case 'rename':
            var name = $parent.find('div.nb_leveWebName').text(),
            el = $('<div class="p20"><input type="text" value="' + name + '" class="inputText" /></div>');
            ConfirmDialog('网页重命名', el, {
                width: 450,
                height: 300,
                scroll: false,
                onBeforeClose: function (fn, type) {
                    if (type == 'confirm') {
                        var value = enToString(el.find('input').val());
                        if (!value) {
                            Alert('名称不能为空！')
                        } else if (getLength(value) > nameMax) {
                            Alert('名称不能超过16个汉字，32个字符！')
                        } else if (value == name) {
                            fn()
                        } else {
                            renamePage(id, value);
                            resetPageName(id, value);
                            fn()
                        }
                    } else {
                        fn()
                    }
                },
                onClose: function () { },
                onConfirm: function () { }
            });
            break;
        case 'copy':
            copyPage(id,
            function (data) {
                insertPage(data).insertAfter($parent);
                resizeScroll(pageScrollContainer)
            });
            break;
        case 'del':
            if ($parent.find('span[role=setHomepage]').hasClass('active')) {
                Alert('首页不能删除！');
                return
            };
            delPage({
                id:
                id,
                name: $parent.find('div.nb_leveWebName').text()
            },
            function () {
                if ($parent.find('span[role="setMenu"]').hasClass('active')) {
                    reloadPageNav()
                };
                $parent.hideRemove();
                resizeScroll(pageScrollContainer);
                var url = pageURL + $parent.data('id');
                closeTab('', url, true)
            });
            break;
        case 'set':
            $parent.trigger(click);
            break;
        case 'clearAppPage':
            Confirm('清除后不可恢复，确定要清除这个页面设置吗？',
            function () {
                $parent.removeClass('set');
                rpcJSON('clearAppPage', {
                    pageId: id
                })
            });
            break
    }
}).delegate('li', click,
function (e) {
    var url = pageURL + $(this).data('id');
    loadPage({
        id: $(this).data('id'),
        name: $(this).find('div.nb_leveWebName').text(),
        url: url
    });
    if (!$('#nav').hasClass('active')) {
        closeNavList()
    };
    $(this).removeClass('new')
});
function loadPage(data) {
    var recentlyData = {
        id: data.id,
        name: data.name || '未命名'
    };
    $HASH['recently'] = removeArray($HASH['recently'], recentlyData);
    $HASH['recently'].unshift(recentlyData);
    if ($HASH['recently'].length > historyMax) {
        $HASH['recently'].pop()
    };
    storage.set('recently_' + $HASH['site']['id'], $HASH['recently']);
    createFrame(data.url, data.name, 'page', data.id)
};
function removeRecently() {
    storage.remove('recently_' + $HASH['site']['id'])
};
function setCustomPage(data) {
    var html = '<div class="nb_leveSetList"><ul>';
    $.each(data,
    function (i, item) {
        html += '<li data-id="' + item.id + '">' + '<span class="nb_leveIcon ' + (item.homePage ? 'active' : '') + '" title="' + (item.homePage ? $lan['homePage'] : $lan['admin']['setHomePage']) + '" role="setHomepage" ><i class="icon-home" ></i></span>' + '<span class="nb_leveIcon ' + (item.navPage ? 'active' : '') + '" title="' + (item.navPage ? $lan['admin']['cancelNavPage'] : $lan['admin']['setNavPage']) + '" role="setMenu"><i class="icon-menu"></i></span>' + '<div class="nb_leveWebName">' + item.name + '</div>' + '<span class="nb_leveTool">' + '<i title="' + $lan['admin']['set'] + '" data-tips="3_t" class="icon-cog" role="set"></i>' + '<i title="' + $lan['admin']['viewURL'] + '" data-tips="3_t" class="icon-link" role="viewUrl"></i>' + '<i title="' + $lan['admin']['rename'] + '" data-tips="3_t" class="icon-pencil" role="rename"></i>' + '<i title="' + $lan['admin']['copy'] + '" data-tips="3_t" class="icon-copy" role="copy"></i>' + '<i title="' + $lan['admin']['delete'] + '" data-tips="3_t" class="icon-remove" role="del"></i>' + '</span>' + '</li>'
    });
    html += '</ul></div>';
    return html
};
function setAppPage(data) {
    var html = '<dl class="nb_leveAppList">';
    $.each(data,
    function (i, item) {
        html += '<dt data-id="' + item.id + '">' + item.name + '</dt>';
        html += '<dd class="nb_leveSetList"><ul>';
        if (item.items && item.items.length) {
            $.each(item.items,
            function (i, appItem) {
                html += '<li data-id="' + appItem.id + '" ' + (appItem.set ? 'class="set"' : '') + '><div class="nb_leveWebName">' + appItem.name + '</div>' + '<span class="nb_leveTool">' + '<i title="' + $lan['admin']['set'] + '" data-tips="3_t" class="icon-cog" role="set"></i>' + '<i title="' + $lan['admin']['viewURL'] + '" data-tips="3_t" class="icon-link" role="viewUrl"></i>' + (appItem.set ? '<i title="' + $lan['admin']['clearAppPage'] + '" data-tips="3_t" class="icon-remove" role="clearAppPage"></i>' : '') + '</li>'
            })
        };
        html += '</ul></dd>'
    });
    html += '</dl>';
    return html
};
function getAppPage() {
    if (!$('#appPage').children().length) return;
    rpcJSON('getAppPage', {},
    function (data) {
        $('#appPage').html(setAppPage(data))
    },
    function () {
        $('#appPage').html(getEmptyContent())
    })
};
function getSiteModule(callBack, errorBack) {
    rpcJSON('getSiteModule', {},
    function (backData) {
        $HASH['siteModule'] = backData;
        fireHandler(callBack)
    },
    errorBack)
};
function resetApp() {
    var items = ['myApp', 'recommendApp'];
    if ($HASH['siteModule']) {
        items.push('appMoudle')
    };
    if ($('#appPage').children().length) {
        items.push('appPage')
    };
    rpcJSON('getSiteApps', {
        items: items
    },
    function (backData) {
        var html = '';
        if (backData.myApp && backData.myApp.length) {
            $.each(backData.myApp,
            function (i, item) {
                html += '<li><a id="' + item.appId + '" href="javascript:;" class="nb_levelLink" url="' + item.manageUrl + '">' + item.name + '</a></li>'
            });
            html += '<hr class="ct_1 hidden-phone" />'
        };
        if (backData.recommendApp && backData.recommendApp.length) {
            $.each(backData.recommendApp,
            function (i, item) {
                html += '<li><a id="' + item.appId + '" href="javascript:;" class="nb_levelLink" url="' + item.manageUrl + '">' + item.name + '</a></li>'
            });
            html += '<hr class="ct_1 hidden-phone" />'
        };
        html += '<li><a href="javascript:;" class="nb_levelLink" url="/?c=admin&a=store"><span class="ct_6">+添加...</span></a></li>';
        $('#appContainer').html(html);
        if (backData.appMoudle) {
            $HASH['siteModule'][$HASH['siteModule'].length - 1]['items'] = backData.appMoudle
        };
        if (backData.appPage) {
            $('#appPage').html(setAppPage(backData.appPage))
        }
    })
};
function reloadPageNav() { };
function savePageTemplate(pageId) {
    createFrame(saveTemplateURL + '/pageId/' + pageId, '保存网页为模板')
};
function openFinder(opts) {
    var opts = $.isFunction(opts) ? {
        callBack: opts
    } : opts,
    options = $.extend(true, {
        extensions: 'jpg,gif,png,jpeg',
        selectCount: 1,
        sign: 'image',
        callBack: $.noop,
        pathList: ['scale_1440', 'scale_768', 'scale_480']
    },
    opts),
    src = finderURL + '/extensions/' + options.extensions + '/selectCount/' + options.selectCount + '/sign/' + options.sign,
    el = $('<div style="height:100%;">' + getContentLoading() + '<iframe id="finderIframe" src="' + src + '" width="100%" height="100%" frameborder="0" scrolling="auto" style="opacity:0"></iframe></div>');
    ConfirmDialog('选择文件', el, {
        width: 1000,
        height: 700,
        scroll: false,
        onBeforeClose: function (fn, type) {
            if (type == 'confirm') {
                if (finderSelected.length) {
                    if (options.pathList) {
                        var getPicPathList = {};
                        $.each(finderSelected,
                        function (i, item) {
                            $.each(options.pathList,
                            function (j, key) {
                                if (!item.all_path[key]) {
                                    if (!getPicPathList[i]) {
                                        getPicPathList[i] = {
                                            id: item.id,
                                            pathList: []
                                        }
                                    };
                                    getPicPathList[i]['pathList'].push(key)
                                }
                            })
                        });
                        if ($.isEmptyObject(getPicPathList)) {
                            fn()
                        } else {
                            rpcJSON('getPicPathList', getPicPathList,
                            function (backData) {
                                for (i in backData) {
                                    finderSelected[i].all_path = backData[i]['all_path']
                                };
                                fn()
                            })
                        }
                    } else {
                        fn()
                    }
                } else {
                    Alert('还没有选择文件')
                }
            } else {
                fn()
            }
        },
        onClose: function () {
            finderSelected = null
        },
        onConfirm: function () {
            options.callBack(finderSelected)
        }
    });
    $('iframe', el).load(function () {
        $('div.loading', el).remove();
        $('iframe', el).animate({
            opacity: 1
        },
        'fast')
    })
};
function selectPageUrl(target, callback) {
    var tree,
    el = $('<div class="pt10" id="pageTreeContainer">' + getContentLoading() + '</div>'),
    dialog = ConfirmDialog('选择本站页面', el, {
        onBeforeClose: function (fn, type) {
            if (type == 'confirm') {
                var selNodes = tree.getSelectedNodes();
                if (!selNodes.length) {
                    Alert('还没有选择页面')
                } else {
                    fn()
                }
            } else {
                fn()
            }
        },
        onConfirm: function () {
            var selNodes = tree.getSelectedNodes(),
            selected = $.map(selNodes,
            function (node) {
                return {
                    id: node.data.key,
                    name: node.data.title,
                    type: node.data.pageType
                }
            })[0];
            id = selected['id'],
            pageurl = selected['type'] == 'customPage' ? '/c/default/pageId/' + id : '/c/default/a/view/ac/' + id;
            selected.href = pageurl;
            if (target) {
                target.val(pageurl)
            };
            if ($.isFunction(callback)) {
                callback(selected)
            }
        }
    });
    rpcJSON('getPageTree', {
        selectMode: 1
    },
    function (data) {
        tree = top.$('#pageTreeContainer').dynatree({
            checkbox: true,
            selectMode: 1,
            children: data,
            onExpand: function () {
                dialog.resizeScroll()
            }
        }).dynatree("getTree");
        dialog.resizeScroll()
    })
};